package yunjiao.javatutorials.lang.concurrent.interrupt;

/**
 * 复杂场景下的中断处理
 *
 * @author yangyunjiao
 */
public class ComplexInterruptExample {
    private volatile boolean shouldStop = false;

    public static void main(String[] args) throws InterruptedException {
        ComplexInterruptExample example = new ComplexInterruptExample();
        Thread worker = new Thread(example.new ComplexTask());
        worker.start();

        // 运行5秒后请求停止
        Thread.sleep(2000);
        worker.interrupt();
        example.shouldStop = true;

        worker.join(2000); // 等待线程结束，最多2秒
        if (worker.isAlive()) {
            System.out.println("线程未及时响应，可能需要强制处理");
        }
    }

    class ComplexTask implements Runnable {
        @Override
        public void run() {
            try {
                while (!shouldStop && !Thread.currentThread().isInterrupted()) {
                    System.out.println("执行复杂任务...");

                    // 模拟包含多个步骤的复杂任务
                    step1();
                    if (Thread.currentThread().isInterrupted()) break;

                    step2();
                    if (shouldStop) break;

                    step3();
                }
            } catch (InterruptedException e) {
                System.out.println("复杂任务被中断");
                Thread.currentThread().interrupt();
            } finally {
                cleanup();
            }
        }

        private void step1() throws InterruptedException {
            System.out.println("执行步骤1");
            Thread.sleep(400);
        }

        private void step2() throws InterruptedException {
            System.out.println("执行步骤2");
            Thread.sleep(400);
        }

        private void step3() throws InterruptedException {
            System.out.println("执行步骤3");
            Thread.sleep(400);
        }

        private void cleanup() {
            System.out.println("清理资源...");
        }
    }
}
